import axios from 'axios'
export default {
  state: {
    list: []
  },
  mutations: {
    updateList (state, payload) {
      state.list = payload
      console.log(state.list)
    }
  },
  getters: {
    total (state) {
      return state.list.reduce((value, item) => {
        value += item.count
        return value
      }, 0)
    },
    totalMoney (state) {
      return state.list.reduce((value, item) => {
        value += item.count * item.price
        return value
      }, 0)
    }
  },
  actions: {
    async getList (ctx) {
      const res = await axios.get('http://localhost:3000/cart')
      console.log(res.data)
      ctx.commit('updateList', res.data)
    },
    updateOne (context, newValue) {
      context.state.list.forEach(item => {
        if (item.id === newValue.id) {
          item.count = newValue.count
        }
      })
    }
  },
  namespaced: true
}
